package com.my.study.utils;

import com.google.common.collect.Lists;
import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.exception.BusinessException;
import com.my.study.service.BusinessInterface;
import com.my.study.service.SendMailService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ThreadExecutorUtil {

    private static ThreadPoolTaskExecutor executor = SpringBeanUtil.getBean(ThreadPoolTaskExecutor.class);

    /**
     * 异步执行不需要返回值(例如：异步调用接口),有返回值
     *
     * @param list
     * @param businessInterface
     */
    public static List batchExecutor(List<String> list, BusinessInterface businessInterface) {
        List objList = new ArrayList();
        // 非空判断
        if (Objects.isNull(list)) {
            return new ArrayList<>();
        }
        List<List<String>> lists = Lists.partition(list, 5);
        lists.forEach(tempList -> {
            ListenableFuture<List> listenableFuture = executor.submitListenable(() -> businessInterface.customBusiness(tempList));
            try {
                objList.addAll(listenableFuture.get());
            } catch (Exception e) {
                throw BusinessException.fail(BusinessExceptionEnum.FAIL.code, "执行失败");
            }
        });
        return objList;
    }

    /**
     * 批量发送邮件
     *
     * @param list
     * @param sendMailService
     */
    public static void batchSendEmail(List<Map<String,String>> list, SendMailService sendMailService) {
        // 非空判断
        if (Objects.isNull(list)) {
            return;
        }
        executor.execute(sendMailService::sendEmail);
    }

    /**
     * 测试方法
     * @param testService
     */
    public static void Test(TestService testService){
        testService.test("","");
    }

    @FunctionalInterface
    public interface TestService{
        void test(String code,String msg);
    }
}
